package com.sxt.practiceapplication.service

import android.content.Context
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.Matrix
import android.media.ImageReader
import com.lzy.okhttputils.OkHttpUtils
import com.lzy.okhttputils.cache.CacheMode
import com.lzy.okhttputils.callback.StringCallback
import com.sxt.practiceapplication.activities.ChangePasswordActivity
import com.sxt.practiceapplication.activities.course.CourseSampleControlVideo
import com.sxt.practiceapplication.common.Urls
import com.sxt.practiceapplication.utils.CommonUtil
import com.sxt.practiceapplication.utils.LogUtil
import com.sxt.practiceapplication.utils.LoginUser
import com.sxt.practiceapplication.utils.camera.CameraUtil
import okhttp3.Call
import okhttp3.Response
import java.io.File
import java.io.FileOutputStream
import java.nio.ByteBuffer
import java.util.*
import java.util.concurrent.CountDownLatch


class GestureCompareService
@JvmOverloads constructor(
        /**
         * 应用上下文
         */
        val context: Context,

        /**
         * 视频播放控制对象
         */
        private val displayPlayer: CourseSampleControlVideo,

        /**
         * 请求成功的处理逻辑部分
         */
        private var handleSuccess: ((String?) -> Unit)? = null
) {
    private val cameraUtil: CameraUtil by lazy {
        displayPlayer.cameraUtil!!
    }

    private var task: TimerTask? = null

    /**
     * 开启姿态识别
     */
    @JvmOverloads
    fun startGestureComparing(handleSuccess: ((String?) -> Unit)? = null, period: Long = 1000) {
        handleSuccess?.let { this.handleSuccess = it }
        task = object : TimerTask() {
            override fun run() {
                val launch = CountDownLatch(2)
                val shotVideo: File = shotVideo(launch)
                val cutCamera: File? = cutCamera(launch)
                cutCamera?.let {
                    launch.await()
                    OkHttpUtils.post(Urls.GESTURE_URL) // 请求方式和请求url
                            .tag(this) // 请求的 tag, 主要用于取消对应的请求
                            .cacheMode(CacheMode.NO_CACHE) // 缓存模式，详细请看缓存介绍
                            .headers("Authorization", LoginUser.getCurrentUserData(context).token)
                            .addFileParams("images", arrayListOf(shotVideo, cutCamera))
                            .execute(object : StringCallback() {
                                override fun onSuccess(result: String?, call: Call?, response: Response?) {
                                    this@GestureCompareService.handleSuccess?.invoke(result)
                                    shotVideo.delete()
                                    cutCamera.delete()
                                }
                            })
                } ?: run { shotVideo.delete() }
            }
        }
        Timer().schedule(task, Date(), period)
    }

    /**
     * 关闭姿态识别
     */
    fun stopGestureComparing() = run { task?.cancel() }

    /**
     * 获取视频截图
     */
    private fun shotVideo(launch: CountDownLatch): File {
        var videoImage = File("${context.filesDir}GSY-${System.currentTimeMillis()}.jpg")
        //获取截图
        try {
            displayPlayer.taskShotPic { bitmap: Bitmap? ->
                if (bitmap != null) {
                    videoImage = CommonUtil.getFile(context, bitmap)
                } else {
                    LogUtil.e("获取视频截图失败")
                }
                launch.countDown()
            }
        } catch (e: Exception) {
        }
        return videoImage
    }

    /**
     * 获取相机cut
     */
    private fun cutCamera(launch: CountDownLatch): File? {
        if (!cameraUtil.isCameraStarted) {
            return null
        }
        val cameraImage = File("${context.filesDir}camera-${System.currentTimeMillis()}.jpg")
        cameraUtil.mImageReader.setOnImageAvailableListener({ reader: ImageReader ->
            val image = reader.acquireLatestImage()
            if (image != null) {
                FileOutputStream(cameraImage).use {
                    val buffer: ByteBuffer = image.planes[0].buffer
                    val data = ByteArray(buffer.remaining())
                    buffer.get(data)
                    it.write(data, 0, data.size)
                    var bitMap = BitmapFactory.decodeFile(cameraImage.absolutePath)
                    val matrix = Matrix()
                    matrix.setScale(-1.0f, 1.0f)
                    bitMap = Bitmap.createBitmap(bitMap, 0, 0, bitMap.width, bitMap.height, matrix, true)
                    FileOutputStream(cameraImage).use { out ->
                        bitMap.compress(Bitmap.CompressFormat.JPEG, 100, out)
                        bitMap.recycle()
                    }
                }
                image.close()
            }
            launch.countDown()
        }, cameraUtil.handler)
        try {
            cameraUtil.capture()
        } catch (e: Exception) {
        }
        return cameraImage
    }
}
